﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.SqlServerCe;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.IO;

namespace KinectProject
{


    public class dbController
    {

        //trial pattern table (1 or more trials)
        VRGETTableAdapters.TrialPatternAdapter tpAdapter;
        VRGET.TrialPatternDataTable tpDataTable;
        VRGET.TrialPatternRow tpRow;

        //individual trials (1 trial)
        VRGETTableAdapters.TrialAdapter tAdapter;
        VRGET.TrialDataTable tDataTable;
        VRGET.TrialRow tRow;

        //Record
        VRGETTableAdapters.RecordAdapter recAdapter;
        VRGET.RecordDataTable recDataTable;
        VRGET.RecordRow recRow;

        //person table
        VRGETTableAdapters.PersonAdapter pAdapter;
        VRGET.PersonDataTable pDataTable;
        VRGET.PersonRow pRow;

        //results
        VRGETTableAdapters.ResultAdapter rAdapter;
        VRGET.ResultDataTable rDataTable;
        VRGET.ResultRow rRow;

        int trialIndex, count;

        LogRow row;
        LogWriter writer;
        //DateTime dt;
        public dbController()
        {

            log.moreTrials = true;
            row = new LogRow();

            log.date = DateTime.Now.Date.ToString();

            if (File.Exists(log.logPath))
            {
                log.newLog = false;
            }
            else
            {
                log.newLog = true;
            }

            writer = new LogWriter(log.logPath);



             


            trialIndex = 1;

            //open connection to apropriate DB tables
            tAdapter = new VRGETTableAdapters.TrialAdapter();
            tpAdapter = new VRGETTableAdapters.TrialPatternAdapter();
            recAdapter = new VRGETTableAdapters.RecordAdapter();
            pAdapter = new VRGETTableAdapters.PersonAdapter();
            rAdapter = new VRGETTableAdapters.ResultAdapter();

            tDataTable = new VRGET.TrialDataTable();
            recDataTable = new VRGET.RecordDataTable();
            tpDataTable = new VRGET.TrialPatternDataTable();
            pDataTable = new VRGET.PersonDataTable();
            rDataTable = new VRGET.ResultDataTable();


            // Setup first trial
            //-------------------------------------------

            //Get table with rows that match tp_id = log.trialPattern
            tpDataTable = tpAdapter.GetDataByID(log.trialPattern + "");

            count = tpDataTable.Rows.Count;
            if (count == 0)
            {
                MessageBox.Show("No Trials to run");
                return;
            }
            //Row that holds Trial Pattern
            tpRow = tpDataTable[0];


            int s;
            int.TryParse(tpRow[trialIndex] + "", out s);
            tDataTable = tAdapter.GetDataById(s);
            tRow = tDataTable[0];
            log.flexion = (string)tRow["Flexion"];
            log.weight = (string)tRow["Weight"];
            log.speed = (string)tRow["Speed"];
            log.trial = tRow.t_id;



            /*

            // create Person
            //---------------------------------------------
            //if no current person...
            //new person row
            pDataTable = pAdapter.GetDataByName(log.fName, log.lName);
            count = pDataTable.Rows.Count;
            if (count == 0)
            {

                //make new person
                pDataTable = pAdapter.GetData();
                pRow = (VRGET.PersonRow)pDataTable.NewRow();
                count = pDataTable.Rows.Count;
                if (count == 0)
                {
                    pRow.p_id = 1;
                }
                else
                {
                    pRow.p_id = pDataTable[count - 1].p_id + 1;
                    //MessageBox.Show("ERROR setting Record ID");
                }
                pRow.First = log.fName;
                pRow.Last = log.lName;
                pDataTable.Rows.Add(pRow);
                pAdapter.Update(pDataTable);
            }
            else
            {
                pRow = pDataTable[0];
            }




            // create record_id (same rec_id throughout trial pattern)
            //------------------------------------------------------
            recDataTable = recAdapter.GetData();
            count = recDataTable.Rows.Count;
            if (count == 0)
            {
                log.recordId = 1;
            }
            else
            {
                log.recordId = recDataTable[recDataTable.Rows.Count - 1].rec_id + 1;

                //MessageBox.Show("ERROR setting Record ID");
            }


            */

        }




        //get next trial from tp, load into log
        public bool getNextValues()
        {

            trialIndex += 1;

            //if there is a next trial

            int s;
            int.TryParse(tpRow[trialIndex] + "", out s);

            if (s != 0)
            {

                tDataTable = tAdapter.GetDataById(s);
                tRow = tDataTable[0];
                log.trial = tRow.t_id;
                log.flexion = (string)tRow["Flexion"];
                log.weight = (string)tRow["Weight"];
                log.speed = (string)tRow["Speed"];
                return true;

            }
            else
            {


                //log.moreTrials = false;
                //Trial has Finished
                //MessageBox.Show("Trial Has Finished");
                log.moreTrials = false;
                return false;

            }

        }


        public void saveResults()
        {


            //if new log, write titles
            if (log.newLog)
            {
                log.newLog = false;
                foreach (string value in log.titles)
                {
                    row.Add(value);
                }

                writer.writeToLog(row);
                row.Clear();

            }



            if (log.writeName)
            {
                log.writeName = false;
                row.Add(log.fName);
                row.Add(log.lName);
                row.Add(log.date);
            }

            row.Add(log.flexion);
            row.Add(log.speed);
            row.Add(log.weight);
            //row.Add(log.audio);
            //row.Add(log.visual);
            row.Add(log.pain + "");
            row.Add(log.harm + "");
            row.Add(log.anxiety + "");
            row.Add(log.epain + "");
            row.Add(log.time + "");

            if (!log.moreTrials)
            {
                writer.writeToLog(row);
                log.writeName = true;
            }



            /*
            // this function writes the current log 
            // values to the database
            //
            // When called, log values are expected to be 
            // the reults of the current iteration of the trial

            pDataTable = pAdapter.GetDataByName(log.fName, log.lName);
            
            //  make and fill results row
            //-------------------------------------------
            rDataTable = rAdapter.GetData();

            rRow = (VRGET.ResultRow)rDataTable.NewRow();
            count = rDataTable.Rows.Count;
            if (count == 0)
            {
                rRow.r_id = "1";
            }
            else
            {
                rRow.r_id = rDataTable[count - 1].r_id + 1;
                //MessageBox.Show("ERROR setting Result ID");
            }

            rRow.vasAnxiety = log.anxiety + "";
            rRow.vasHarm    = log.harm    + "";
            rRow.vasPain    = log.pain    + "";
            rRow.vasEPain   = log.epain   + "";
            rDataTable.Rows.Add(rRow);
            rAdapter.Update(rDataTable);

            int x;
            int.TryParse(rRow.r_id, out x);


            //make and fill record
            // (a record ties a result, person, and trial 
            //  together.)
            recDataTable = recAdapter.GetData();
            recRow = (VRGET.RecordRow)recDataTable.NewRow();
            recRow.rec_id = (int)log.recordId;
            recRow.p_id   = pDataTable[0].p_id;
            recRow.t_id   = (int)log.trial;
            recRow.r_id   = x;
            recDataTable.Rows.Add(recRow);
            recAdapter.Update(recDataTable);
            */
            
        }//End saveResults()



        internal void close()
        {
            writer.writeToLog(row);
            writer.Close();
            writer.Dispose();
        }

    }//end class dbcontroller





    public class LogWriter : StreamWriter
    {
      
        public LogWriter(String fileName):base(fileName, true){  
            //throws constructor to StreamWriter()

        }
        
        //takes row ( a list of strings ) and parses with ',' and writes to logWriter path 
        public void  writeToLog(LogRow row){

            StringBuilder stringB = new StringBuilder();
            
            bool first = true;

            //go down list of strings
            foreach (string cell in row)
            {
                if(first){
                    stringB.Append(cell);
                    first = false;
                    continue;
                }
                stringB.Append(',');
                stringB.Append(cell);

            }
            row.text = stringB.ToString();
            WriteLine( row.text );
        }
    }
    public class LogRow : List<string>
    {
        public string text { get; set; }
    }

}//END namespace


